package com.alog.yzd.bookmall.web.servlet.admin.book;

import com.alog.yzd.bookmall.domain.book.Book;
import com.alog.yzd.bookmall.domain.catagory.Catagory;
import com.alog.yzd.bookmall.service.book.BookService;
import com.alog.yzd.bookmall.service.catagory.CatagoryService;
import com.alog.yzd.commons.CommonUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/1/11 10:03
 * @Description:
 */
public class AdminAddBookServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setFileSizeMax(80 * 1024);

        List<FileItem> fileItemList = null;
        try {
            fileItemList = sfu.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
            error("上传的文件超过了80KB",req, resp);
            return;
        }

        Map<String, Object> map = new HashMap<>();
        for(FileItem item : fileItemList){
            if(item.isFormField()){
                map.put(item.getFieldName(), item.getString("utf-8"));
            }
        }

        Book book = CommonUtils.toBean(map, Book.class);
        Catagory catagory = CommonUtils.toBean(map, Catagory.class);
        book.setCatagory(catagory);

        FileItem fileItem = fileItemList.get(1);
        String filename = fileItem.getName();
        int index = filename.lastIndexOf("\\");
        if(index != -1){
            filename = filename.substring(index + 1);
        }
        filename = CommonUtils.uuid() + "_" + filename;
        if(!filename.toLowerCase().endsWith(".jpg")){
            error("上传的图片必须是JPG", req, resp);
        }

        String savePath = this.getServletContext().getRealPath("/book_img");//WebRoot/book_image的路径
        File dest = new File(savePath, filename);
        try {
            fileItem.write(dest); //不能调用多次
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        book.setImage_w("book_img/" + filename);

        fileItem = fileItemList.get(2);
        filename = fileItem.getName();
        index = filename.lastIndexOf("\\");
        if(index != -1){
            filename = filename.substring(index + 1);
        }
        filename = CommonUtils.uuid() + "_" + filename;
        if(!filename.toLowerCase().endsWith(".jpg")){
            error("上传的图片必须是JPG", req, resp);
        }

        savePath = this.getServletContext().getRealPath("/book_img");//WebRoot/book_image的路径
        dest = new File(savePath, filename);
        try {
            fileItem.write(dest); //不能调用多次
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        book.setImage_b("book_img/" + filename);

        book.setBid(CommonUtils.uuid());
        BookService bookService = new BookService();
        bookService.add(book);

        req.setAttribute("msg", "添加图书成功");
        req.getRequestDispatcher("/adminjsps/admin/msg.jsp").forward(req, resp);
    }

    private void error(String msg, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("msg", msg);
        req.setAttribute("parents", new CatagoryService().findParents());
        req.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(req, resp);
    }

}
